package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Standard;
import com.example.springboot.entity.Standard;
import com.example.springboot.entity.User;
import com.example.springboot.service.StandardService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/standard")
public class StandardController {

    @Autowired
    StandardService standardService;
    
    /**
     * 新增信息
     */
    @HoneyLogs(operation ="标准的导入导出", type = LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Standard standard) {
//        standard.setTime(DateUtil.now());   //  2023-10-24 21:28:12
        standardService.save(standard);
        return Result.success();
    }

    /**
     * 修改信息
     */
    @HoneyLogs(operation ="标准的导入导出", type = LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Standard standard) {
        standardService.updateById(standard);
        return Result.success();
    }

    /**
     * 删除信息
     */
    @HoneyLogs(operation ="标准的导入导出", type = LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        standardService.removeById(id);
        return Result.success();
    }


    /**
     * 批量删除信息
     */
    @HoneyLogs(operation ="标准的导入导出", type = LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        standardService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 查询全部信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Standard> standardList = standardService.list(new QueryWrapper<Standard>());
        return Result.success(standardList);
    }

    /**
     * 根据ID查询信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Standard standard = standardService.getById(id);
        return Result.success(standard);
    }


    /**
     * 多条件模糊查询信息
     * pageNum 当前的页码
     * pageSize 每页查询的个数
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String name,
                               @RequestParam String region,
                               @RequestParam String type,
                               @RequestParam String waterOutput) {
        QueryWrapper<Standard> queryWrapper = new QueryWrapper<Standard>();
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(region), "region", region);
        queryWrapper.like(StrUtil.isNotBlank(type), "type", type);
        queryWrapper.like(StrUtil.isNotBlank(waterOutput), "water_output", waterOutput);
        Page<Standard> page = standardService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Standard> records = page.getRecords();
        return Result.success(page);
    }

    /**
     * 批量导出数据
     */
    @GetMapping("/export")
    public void  exportData(@RequestParam(required = false) String name,
                            @RequestParam(required = false) String region,
                            @RequestParam(required = false) String type,
                            @RequestParam(required = false) String waterOutput,
                            @RequestParam(required = false) String illumination,
                            @RequestParam(required = false) String temperature,
                            @RequestParam(required = false) String soilMoisture,
                            @RequestParam(required = false) String airHumidity,
                            @RequestParam(required = false) String ids,
                            HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<Standard> list = new ArrayList<>();
        QueryWrapper<Standard> queryWrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(ids)){    //["1" , "2" , "3" , "4"]  => [1,2,3,4]
            List<Integer> idsArr1 = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
            queryWrapper.in("id",idsArr1);
        }else {
            //第一种  全部导出/条件导出
            queryWrapper.like(StrUtil.isNotBlank(name), "name" ,name);
            queryWrapper.like(StrUtil.isNotBlank(region), "region" ,region);
            queryWrapper.like(StrUtil.isNotBlank(type), "type" ,type);
            queryWrapper.like(StrUtil.isNotBlank(waterOutput), "water_output" ,waterOutput);
            queryWrapper.like(StrUtil.isNotBlank(temperature), "temperature" ,temperature);
            queryWrapper.like(StrUtil.isNotBlank(soilMoisture), "soil_moisture" ,soilMoisture);
            queryWrapper.like(StrUtil.isNotBlank(airHumidity), "air_humidity" ,airHumidity);
            queryWrapper.like(StrUtil.isNotBlank(illumination), "illumination" ,illumination);
        }
        list = standardService.list(queryWrapper);  //查询出当前User表的所有数据
        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("点检标准表","UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();

    }

    /**
     * 批量导入
     * @param file 传入的excel文件对象
     * @return  导入结果
     */
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Standard> standardList = reader.readAll(Standard.class);
        //写入数据到数据库
        try {
           standardService.saveBatch(standardList);
        }catch (Exception e) {
            e.printStackTrace(); //打印错误信息
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }


}

